package com.blue.gateway.paycore.wxpay.pay;

import com.alibaba.fastjson.JSON;
import com.blue.gateway.annotation.Channel;
import com.blue.gateway.common.Request;
import com.blue.gateway.common.response.PayResponse;
import com.blue.gateway.config.BaseChannelConfig;
import com.blue.gateway.config.WxConfig;
import com.blue.gateway.paycore.wxpay.WxPayConstants;
import com.blue.gateway.dto.Result;
import com.blue.gateway.dto.ResultWrapper;
import com.blue.gateway.enums.PayChannelEnum;
import com.blue.gateway.enums.ServiceChannelEnum;
import com.blue.gateway.utils.BigDecimalUtil;
import com.blue.gateway.utils.RandomUtil;
import com.blue.gateway.utils.XmlUtil;
import com.blue.gateway.utils.http.HttpClientsUtil;
import com.blue.gateway.utils.sign.WxPaySignature;
import com.blue.gateway.common.request.PayRequest;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author xiaoyiming
 * @date 2020/5/3 19:15
 * @depiction 微信支付接口
 * 扫码下单:https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=6_5
 */
@Slf4j
@Channel(PayChannel = PayChannelEnum.WX_QR, ServiceChannel = ServiceChannelEnum.PAY)
public class WxPayQrService extends WxPayService {

    @Override
    public Result validate(Request request) {
        return super.validate(request);
    }


    @Override
    public BaseChannelConfig getConfig(Request request) {
        return super.getConfig(request);
    }

    /**
     * <xml>
     * <appid>wxd898fcb01713c658</appid>
     * <body>测试一下</body>
     * <mch_id>1483469312</mch_id>
     * <nonce_str>rTe7j61Fq8LECpBQ</nonce_str>
     * <notify_url>http://vqcjt4.natappfree.cc/notify_wx</notify_url>
     * <out_trade_no>27809811237111</out_trade_no>
     * <sign>0DCC9A3D4DD26D3468109E29856CA07B</sign>
     * <spbill_create_ip>8.8.8.8</spbill_create_ip>
     * <total_fee>1</total_fee>
     * <trade_type>NATIVE</trade_type>
     * </xml>
     *
     * @param request
     * @param channelConfig
     * @return
     */
    @Override
    public String generateParams(Request request, BaseChannelConfig channelConfig) {
        PayRequest payRequest = (PayRequest) request;
        WxConfig wxConfig = (WxConfig) channelConfig;

        SortedMap<String, String> params = new TreeMap<>();
        params.put("appid", wxConfig.getAppId());
        params.put("mch_id", wxConfig.getMchId());
        params.put("nonce_str", RandomUtil.getRandomStr());
        params.put("body", payRequest.getSubject());
        params.put("out_trade_no", payRequest.getOutTradeNo());
        params.put("total_fee", BigDecimalUtil.toUnitFen(payRequest.getTotalAmount()));
        params.put("spbill_create_ip", payRequest.getSpbillCreateIp());
        params.put("notify_url", payRequest.getNotifyUrl());
        params.put("trade_type", WxPayConstants.TRADE_TYPE_NATIVE);
        String sign = WxPaySignature.sign(params, wxConfig.getParterKey());
        params.put("sign", sign);
        return XmlUtil.mapToXML(params);
    }

    @Override
    public String execute(String requestParams, BaseChannelConfig channelConfig) {
        // 发送请求
        String executeResult = null;
        try {
            executeResult = HttpClientsUtil.httpClientPost(WxPayConstants.WX_PAY_GATEWAY, requestParams);
        } catch (Exception e) {
            // do nothing
        }
        return executeResult;
    }

    /**
     * <xml>
     * <return_code><![CDATA[SUCCESS]]></return_code>
     * <return_msg><![CDATA[OK]]></return_msg>
     * <appid><![CDATA[wxd898fcb01713c658]]></appid>
     * <mch_id><![CDATA[1483469312]]></mch_id>
     * <nonce_str><![CDATA[2pTOgXCdTsUcDo2e]]></nonce_str>
     * <sign><![CDATA[64BB3B2DF7733357804B0B95D027D7F5]]></sign>
     * <result_code><![CDATA[SUCCESS]]></result_code>
     * <prepay_id><![CDATA[wx05174735666162375bc26c741613819800]]></prepay_id>
     * <trade_type><![CDATA[NATIVE]]></trade_type>
     * <code_url><![CDATA[weixin://wxpay/bizpayurl?pr=KJc6gds]]></code_url>
     * </xml>
     *
     * @param executeResult
     * @return
     */
    @Override
    public Result analysisResult(String executeResult) {
        PayResponse payResponse = new PayResponse();
        Map<String, String> result = XmlUtil.toMap(executeResult);
        payResponse.setMsg(result.get("return_msg"));
        payResponse.setData(JSON.toJSONString(result));
        if (WxPayConstants.SUCCESS.equals(result.get("return_code"))) {
            payResponse.setPayUrl(result.get("code_url"));
            return ResultWrapper.success(payResponse);
        }

        return ResultWrapper.fail(payResponse);
    }
}
